import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'
import { query } from '~/server/utils/db'
import type { OkPacket, RowDataPacket } from 'mysql2'
import jwt from 'jsonwebtoken'

const JWT_SECRET = process.env.JWT_SECRET || 'your-strong-secret-key-here'
const REFRESH_SECRET = JWT_SECRET + '_REFRESH'

async function validateRefreshToken(userId: number, token: string): Promise<boolean> {
  try {
    const sql = `
      SELECT id 
      FROM refresh_tokens 
      WHERE user_id = ? 
        AND token = ? 
        AND expires_at > NOW() 
        AND revoked = 0
      LIMIT 1
    `

    const { results } = await query<RowDataPacket[]>(sql, [userId, token])

    if (!results || results.length === 0) {
      return false
    }

    const revokeSql = 'UPDATE refresh_tokens SET revoked = 1 WHERE id = ?'
    await query<OkPacket>(revokeSql, [results[0].id])

    return true

  } catch (error) {
    console.error('验证刷新令牌失败:', error)
    return false
  }
}

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { refreshToken } = body

  if (!refreshToken) {
    return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '需要 refreshToken')
  }

  try {
    const decoded = jwt.verify(refreshToken, REFRESH_SECRET) as jwt.JwtPayload & { userId?: number, user_id?: string }

    if (!decoded.userId || !decoded.user_id) {
      return sendErrorResponse(event, ResponseCode.UNAUTHORIZED, '无效的 refreshToken')
    }

    const isValid = await validateRefreshToken(decoded.userId, refreshToken)
    if (!isValid) {
      return sendErrorResponse(event, ResponseCode.UNAUTHORIZED, '无效的 refreshToken')
    }

    const sql = `SELECT * FROM user WHERE user_id = ?`
    const { results } = await query<RowDataPacket[]>(sql, [decoded.userId])
    const user = results[0]

    if (!user) {
      return sendErrorResponse(event, ResponseCode.NOT_FOUND, '用户不存在')
    }

    const newAccessToken = jwt.sign(
      { userId: user.id, user_id: user.user_id, role: user.role },
      JWT_SECRET,
      { expiresIn: '1h' }
    )

    const newRefreshToken = jwt.sign(
      { userId: user.id, user_id: user.user_id },
      REFRESH_SECRET,
      { expiresIn: '7d' }
    )

    // 存储新的 refreshToken
    const storeSql = `
      INSERT INTO refresh_tokens (user_table_id, user_id, token, expires_at)
      VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 7 DAY))
    `
    await query<OkPacket>(storeSql, [user.id, user.user_id, newRefreshToken])

    return sendSuccessResponse(event, {
      accessToken: newAccessToken,
      refreshToken: newRefreshToken
    }, 'Token 刷新成功')

  } catch (err) {
    console.error('刷新 Token 失败:', err)
    return sendErrorResponse(
      event,
      ResponseCode.UNAUTHORIZED,
      '无效或过期的 refreshToken'
    )
  }
})